# encoding: utf-8
"""
将用户手写字节码写入文件，
不对字节码做任何验证，假设字节码完全正确
"""
import sys
import os
import pickle
from os.path import join, dirname
from Error.Error import send_error


def byte_code(path: str) -> None:
    """
    将用户手写字节码写入文件
    """
    global temp
    path = os.path.abspath(path)
    compile_name = os.path.splitext(os.path.split(path)[1])[0] + ".ctree"
    buildpath = join(dirname(path), compile_name)
    try:
        with open(buildpath, "wb") as file, open(path, encoding="utf-8") as openfile:
            # 利用exec的特性将字符串转化为元组
            exec(
                """global temp
temp = %s"""
                % openfile.read()
            )
            file.write(pickle.dumps(temp))
    except FileNotFoundError:
        # 顺便清理掉垃圾
        os.remove(buildpath)
        send_error("OpenFileError", path)

    except FileExistsError:
        os.remove(buildpath)
        byte_code(path)
